package com.aisafer.fms.service.impl;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aisafer.fms.config.AttachConfig;
import com.aisafer.fms.domain.StsConfig;
import com.aliyun.oss.OSSClient;

/**
 * @author stevin
 *
 */
public class FmsPool {

	private static final Logger log = LoggerFactory.getLogger(FmsPool.class);

	AttachConfig attachConfig;

	public FmsPool(AttachConfig attachConfig) {
		this.attachConfig = attachConfig;
	}

	public PoolClient<OSSClient> getOssClient(StsConfig stsConfig) {
		try {
			return createPoolClient(stsConfig);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return createPoolClient(stsConfig);
		}
	}

	private PoolClient<OSSClient> createPoolClient(StsConfig stsConfig) {
		OSSClient ossClient = new OSSClient(getUrl(stsConfig), stsConfig.getUsername(),
				stsConfig.getPassword());
		PoolClient<OSSClient> opc = new PoolClient<OSSClient>(false, ossClient, new Date(), new Date());
		opc.setKey(com.aisafer.fms.utils.UUId.getUUid());
		return opc;
	}

	private String getUrl(StsConfig stsConfig) {
		return stsConfig.getAddress();
	}

	public void shutdown(PoolClient<OSSClient> poolClient) {
		if (poolClient.getClient() != null) {
			poolClient.getClient().shutdown();
		}

	}

	public static FmsPool getOssPool(AttachConfig attachConfig) {
		return new FmsPool(attachConfig);
	}

}
